#定义数据可以工具类
import pymysql


class DBTools(object):
    @classmethod
    def create_conn(cls):
        conn = pymysql.connect(host="211.103.136.244",
                               port=7061, user="student", password="iHRM_student_2021",
                               database="ihrm", charset="utf8")
        # 不能遗漏
        return conn
    @classmethod
    def query_one(cls, sql):
        my_cursor = None
        my_conn = None
        res=None
        try:
            # 创建连接,借助类名,调用  类方法create_conn
            my_conn = DBTools.create_conn()
            # 创建游标
            my_cursor = my_conn.cursor()
            # 提取数据
            my_cursor.execute(sql)
            # 查一条记录
            res = my_cursor.fetchone()
        except Exception as e:
            print("错误类型:",str(e))
        finally:
            # 关闭游标
            my_cursor.close()
            # 关闭连接
            my_conn.close()
            return res
    @classmethod
    def db_uid(cls,sql):
        my_conn=None
        my_cursor=None
        try:
            # 创建连接,借助类名,调用  类方法create_conn
            my_conn = DBTools.create_conn()
            # 创建游标
            my_cursor = my_conn.cursor()
            # 提取数据
            my_cursor.execute(sql)
            print("Affected rows", my_conn.affected_rows())
            # 提交数据
            my_conn.commit()
            # 结果描述信息

        except Exception as e:
            # 回滚数据
            print("错误类型:", str(e))
            my_conn.rollback()

        finally:
            # 关闭游标
            my_cursor.close()
            # 关闭连接
            my_conn.close()


